<template>
  <el-button @click="startNewConversation" round>开启新对话</el-button>
  <Conversations
      v-model:active="activeKey6"
      :items="conversations"
      show-to-top-btn
      show-built-in-men
      row-key="key"
      groupable
      style="background: #f9fafb;width: 280px;"
      :show-tooltip="true"
      @change="handleChange"
      :load-more="loadMoreItems"
      :load-more-loading="isLoading"
  />

</template>
<script setup>
import {ref} from "vue";
import {aiConversationPage,} from "@/views/system/ai/js/AiConversationRequest.js";
import {AiUtil} from "@/utils/AiUtil.js";
import {aiConversationMessageList} from "@/views/system/ai/js/AiConversationMessageRequest.js";
import {useAiLocalStore} from "@/store/AiLocalStore.js";

const aiLocalStore = useAiLocalStore();

onMounted(() => {
  getPage()
})

const startNewConversation = () => {
  aiLocalStore.startNewConversation()
  getPage()
}
const page = ref({
  hasNext: true,
  currentPage: 1,
  pageSize: 30
})
const conversations = ref([]);

const handleChange = (item) => {
  aiConversationMessageList({conversationId: item.key}).then(res => {
    if (res.success) {
      let temp = []
      if (res.data.length > 0) {

        res.data.forEach(item => {
          let aiBubble = AiUtil.buildBubble(item.role, item.role === 'assistant' ? 'strat' : 'end', item.content, false, true,
              'https://img.ixintu.com/download/jpg/201911/e25b904bc42a74d7d77aed81e66d772c.jpg!con');
          temp.push(aiBubble)
        })
      }
      aiLocalStore.clearBubbles()
      aiLocalStore.bubbles = temp
    }
  }).finally(() => {
    aiLocalStore.conversionId = item.key
  })
}

const getPage = (newPage = page.value.currentPage, newSize = page.value.pageSize) => {
  aiConversationPage({
    pageNum: newPage,
    pageSize: newSize,
  }).then(res => {
    if (res.success) {
      if (res.data.records.length === 0 || res.data.length < 0) {
        page.value.hasNext = false
        return
      }
      res.data.records.forEach((record) => {
        conversations.value.push(AiUtil.buildConversationItem(record.conversationId, record.title, record.createTime))
      })

    }
  }).finally(() => {
    isLoading.value = false;
  })
}
const activeKey6 = ref('l1');


// 加载更多处理
const isLoading = ref(false);

const loadMoreItems = () => {
  if (!page.value.hasNext) {
    return;
  }
  if (isLoading.value)
    return;
  isLoading.value = true;
  page.value.currentPage += 1
  getPage()
}

</script>


<style scoped lang="less"></style>